package com.mobbanana.gameHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.kuaiyouxi.gamepad.sdk.shell.assist.SDKAssist;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Locale;

/**
 * @Description
 * @Author imchen
 * @CreateTime 2019/11/13 16:10
 */
public class GameUtils {

    private static long sAppRunDuration = 0;
    private static final long MIX_SHOW_TIME = 20 * 1000;
    private static final long MIX_SHOW_INTERVAL = 20 * 1000;
    private static WeakReference<Activity> activityWeakReference;
    private static final String SP_FILE = "game_util";
    private static long showAt = 0;
    private static int IIR = 3;
    private static int IIR_Cursor = 1;
    private static final String TAG = "GameUtils";
    private static final String SDK_CLASS = "com.kuaiyouxi.gamepad.sdk.shell.assist.SDKAssist";

    private static HashMap<String, Integer> watchMaxMap;

    public static String SHOW_REGULAR = "2,2,3";
    public static final String REGULAR_KEY = "regular_index";
    private static int adShowAt = 0;


    public static void initOnActivity(Activity activity) {
        sAppRunDuration = System.currentTimeMillis();
        activityWeakReference = new WeakReference<>(activity);
        initWatchMaxMap();
        DataUtil.initGameData(activity);
    }

    private static void initWatchMaxMap() {
        watchMaxMap = new HashMap<>();
        watchMaxMap.put("uid", 1);
        watchMaxMap.put("uid2", 2);
        watchMaxMap.put("uid3", 3);
        watchMaxMap.put("uid4", 5);
        watchMaxMap.put("uid5", 7);
        watchMaxMap.put("uid6", 8);
        watchMaxMap.put("uid7", 10);
    }

    private static int getWatchMax(String uid) {
        if (watchMaxMap == null || !watchMaxMap.containsKey(uid)) {
            return 5;
        }
        return watchMaxMap.get(uid);
    }

    public static long getAppRunDuration() {
        return sAppRunDuration;
    }

    /**
     * 程序启动前20秒不会弹插屏
     */
    public static void showLogAvoidHomeInterstitial() {
        if ((System.currentTimeMillis() - sAppRunDuration) > MIX_SHOW_TIME) {
            activityWeakReference.get().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SDKAssist.showLog();
                }
            });
        }
    }

    /**
     * 周期范围内弹一次插屏，否则不能弹出，适用于无法控制弹出时机的函数
     */
    public static void showLogLimit() {
        if (System.currentTimeMillis() - showAt > MIX_SHOW_INTERVAL) {
            showLogAvoidHomeInterstitial();
            showAt = System.currentTimeMillis();
        }
    }

    public static void showAdIIR() {
        if (IIR_Cursor < IIR) {
            showLogOnUIThread();
        } else {
            showVideoOnUIThread();
            IIR_Cursor = 1;
        }
    }

    /**
     * 在UI线程展示插屏
     */
    public static void showLogOnUIThread() {
        if (hasClass(activityWeakReference.get()))
            activityWeakReference.get().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SDKAssist.showLog();
                }
            });
    }

    public static void showFullScreenVideoOnUIThread() {
        if (hasClass(activityWeakReference.get()))
            activityWeakReference.get().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SDKAssist.showLog();
                }
            });
    }

    public static void showVideoOnUIThread() {
        if (hasClass(activityWeakReference.get()))
            activityWeakReference.get().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SDKAssist.showVideoAd();
                }
            });
    }

    public static void showDialog(final String msg) {
        activityWeakReference.get().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(activityWeakReference.get());
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                builder.show();
            }
        });

    }

    public static boolean showRewardWithCount(String uid) {
        int count = getInt(uid, 0);
        int max = getWatchMax(uid);
        count++;
        if (count >= max) {
            return true;
        }
        showDialog("再看" + (max - count) + "次视频解锁奖励!");
        putInt(uid, count);
        return false;
    }

    public static boolean showRewardWithCount(String uid, boolean isReset) {
        boolean result = showRewardWithCount(uid);
        if (result && isReset) {
            resetCount(uid);
        }
        return result;
    }

    public static void resetCount(String uid) {
        putInt(uid, 0);
    }

    public static boolean putString(String key, String value) {
        SharedPreferences settings = activityWeakReference.get().getSharedPreferences(SP_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    public static String getString(String key, String defaultValue) {
        SharedPreferences settings = activityWeakReference.get().getSharedPreferences(SP_FILE, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);
    }

    public static boolean putInt(String key, int value) {
        SharedPreferences settings = activityWeakReference.get().getSharedPreferences(SP_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        return editor.commit();
    }

    public static int getInt(String key, int defaultValue) {
        SharedPreferences settings = activityWeakReference.get().getSharedPreferences(SP_FILE, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);
    }

    private void reward() {

    }

    private void failed() {

    }

    private static boolean hasClass(Context context) {
        try {
            context.getClassLoader().loadClass(SDK_CLASS);
            return true;
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "hasClass: "+e.getMessage());
        }
        return false;
    }

    public void test(Activity activity) {
        initOnActivity(activity);
        showLogAvoidHomeInterstitial();

        String uid = "1234";
        if (showRewardWithCount(uid, false)) {
            reward();
        } else {
            failed();
        }
    }

    public String convertJSON() {
        String jsonStr = "[\"{\\\"cpm\\\":650,\\\"adWidth\\\":\\\"320\\\",\\\"class\\\":\\\"com.mopub.mobileads.GooglePlayServicesInterstitial\\\",\\\"network_name\\\":\\\"admob_native\\\",\\\"adHeight\\\":\\\"480\\\",\\\"precision\\\":\\\"publisher_defined\\\",\\\"adUnitID\\\":\\\"ca-app-pub-4802411449673199\\/8899993078\\\"}\"]";
        return jsonStr;
    }

    public static void showAdWithRegular() {
        String[] showRegulars = SHOW_REGULAR.split(",");
//        int regularIndex = SPUtil.getInt(activityWeakReference.get(), REGULAR_KEY, 0);
        int adType = Integer.parseInt(showRegulars[adShowAt]);
        LogUtil.d("Regular index: " + adShowAt + " adType: " + adType);
        if (adType == 1) {
//            插屏
            showLogOnUIThread();
        } else if (adType == 2) {
//全屏插屏
            showFullScreenVideoOnUIThread();
        } else if (adType == 3) {
//            激励视频
            showVideoOnUIThread();
        }
        adShowAt += 1;
        if (adShowAt >= showRegulars.length) {
            adShowAt = 0;
        }
//        SPUtil.putInt(activityWeakReference.get(), REGULAR_KEY, regularIndex);
    }

    public static void setDefaultLanguage(Context context, String language) {
        Locale locale = new Locale(language);
        try {
            Class clz = context.getClassLoader().loadClass("java.util.Locale$NoImagePreloadHolder");
            Field field = clz.getDeclaredField("defaultLocale");
            field.setAccessible(true);
            field.set(null, locale);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtil.d("After reflect field:--> " + Locale.getDefault());
    }


    public static String getVersionName(Context context) {
        PackageInfo info;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
}
